package com.ruoyi.jihuo.utils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Slf4j
public class ImageUtils {

    public static Thumbnails.Builder<File> getBuilder(String originalImagePath) {
        try {
            // 读取原始图片以获取尺寸
            BufferedImage originalImage = ImageIO.read(new File(originalImagePath));
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            // 返回带有原始尺寸的构建器
            return Thumbnails.of(originalImagePath)
                    .size(width, height);
        } catch (IOException e) {
            log.error("读取原始图片失败: {}", originalImagePath, e);
            throw new RuntimeException("无法读取图片文件", e);
        }
    }

    public static void buildToFile(Thumbnails.Builder<File> fileBuilder, String outputFilePath, String outputFileType) {
        try {
            // 确保输出目录存在
            File outputFile = new File(outputFilePath);
            File parentDir = outputFile.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs(); // 创建所有必要的父目录
            }

            fileBuilder
                    .outputFormat(outputFileType)
                    .toFile(outputFilePath);
        } catch (IOException e) {
            log.error("图片处理异常", e);
        }
    }

    public static void rotateImage(Thumbnails.Builder<File> fileBuilder, boolean needHorizontalFlip, boolean needVerticalFlip) {
        if (needHorizontalFlip && needVerticalFlip) {
            fileBuilder.addFilter(new FlipBothFilter());
        }
        if (needHorizontalFlip) {
            fileBuilder.addFilter(new HorizontalFlipFilter());
        }
        if (needVerticalFlip) {
            fileBuilder.addFilter(new VerticalFlipFilter());
        }
    }

    public static void compressImage(Thumbnails.Builder<File> fileBuilder, int compressibility) {
        fileBuilder
                .outputQuality(compressibility * 0.01f);  // 30%质量
    }

    public static void imageWatermark(Thumbnails.Builder<File> fileBuilder,String imageWaterPath, int opacity,  Positions position) {
        BufferedImage watermarkImg = null;
        try {
            // 加载水印图片
            watermarkImg = ImageIO.read(new File(imageWaterPath));
        } catch (Exception e) {
            log.error("读取图片异常", e);
        }
        fileBuilder
                .scale(1)                  // 保持原始尺寸
                .watermark(
                        position, // 水印位置（右下角）
                        watermarkImg,           // 水印图片
                        opacity * 0.01f                    // 透明度 (0.0完全透明 - 1.0完全不透明)
                );// 输出质量
    }

    public static void textWatermark(Thumbnails.Builder<File> fileBuilder, String textWater, int opacity, Positions position) {
        fileBuilder
                .addFilter(new TextWatermarkFilter(
                        textWater,    // 水印文字
                        new Font("Arial", Font.BOLD, 40), // 字体
                        Color.WHITE,         // 文字颜色
                        opacity * 0.01f,                // 透明度
                        position,
                        10, 10               // 边距
                ));// 输出质量;
    }

    // 自定义文字水印过滤器
    static class TextWatermarkFilter implements ImageFilter {
        private final String text;
        private final Font font;
        private final Color color;
        private final float alpha;
        private final Positions position;
        private final int xOffset;
        private final int yOffset;

        public TextWatermarkFilter(String text, Font font, Color color,
                                   float alpha, Positions position,
                                   int xOffset, int yOffset) {
            this.text = text;
            this.font = font;
            this.color = color;
            this.alpha = alpha;
            this.position = position;
            this.xOffset = xOffset;
            this.yOffset = yOffset;
        }

        @Override
        public BufferedImage apply(BufferedImage img) {
            Graphics2D g = img.createGraphics();

            // 设置绘制参数
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setFont(font);
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

            // 计算水印位置
            FontMetrics metrics = g.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getHeight();

            int x = xOffset;
            int y = yOffset;

            switch (position) {
                case TOP_LEFT:
                    y += textHeight;
                    break;
                case TOP_RIGHT:
                    x = img.getWidth() - textWidth - xOffset;
                    y += textHeight;
                    break;
                case BOTTOM_LEFT:
                    y = img.getHeight() - yOffset;
                    break;
                case BOTTOM_RIGHT:
                    x = img.getWidth() - textWidth - xOffset;
                    y = img.getHeight() - yOffset;
                    break;
                case CENTER:
                    x = (img.getWidth() - textWidth) / 2;
                    y = (img.getHeight() - textHeight) / 2 + metrics.getAscent();
                    break;
            }

            // 绘制文字
            g.drawString(text, x, y);
            g.dispose();

            return img;
        }
    }

    // 水平翻转过滤器
    static class HorizontalFlipFilter implements ImageFilter {
        @Override
        public BufferedImage apply(BufferedImage img) {
            AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
            tx.translate(-img.getWidth(null), 0);
            return new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);
        }
    }

    // 垂直翻转过滤器
    static class VerticalFlipFilter implements ImageFilter {
        @Override
        public BufferedImage apply(BufferedImage img) {
            AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
            tx.translate(0, -img.getHeight(null));
            return new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);
        }
    }

    // 水平+垂直翻转（相当于180度旋转）
    static class FlipBothFilter implements ImageFilter {
        @Override
        public BufferedImage apply(BufferedImage img) {
            AffineTransform tx = AffineTransform.getScaleInstance(-1, -1);
            tx.translate(-img.getWidth(null), -img.getHeight(null));
            return new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(img, null);
        }
    }
}
